//
//  MainTabBar.m
//  weather
//
//  Created by 大L君的无敌战舰 on 16/3/31.
//  Copyright © 2016年 bigL.com. All rights reserved.
//

#import "MainTabBarView.h"
#import "MainTabBarButton.h"


@interface MainTabBarView ()

/* 保存tabBar中按钮状态 */
@property (strong, nonatomic) NSMutableArray * buttonArray;

/* tabBar背景 */
@property (strong, nonatomic) UIImageView * backgroundView;

/* 保存上一次选中的按钮 */
@property (strong, nonatomic) UIButton * preButton;

@end

@implementation MainTabBarView

/**
 *  懒加载buttonArray
 *  添加子按钮
 */
-(NSMutableArray *)buttonArray
{
    if (!_buttonArray) {
        _buttonArray = [NSMutableArray array];
        //添加子按钮
        [self loadChildWidget];
    }
    return _buttonArray;
}



/**
 *  加载子控件
 *   1.背景View
 *   2.子按钮
 */
-(void)loadChildWidget
{
    for (NSInteger i = 0; i < self.tabBarItemArray.count; i++) {
        //创建子按钮
        MainTabBarButton * btn = [MainTabBarButton buttonWithType:UIButtonTypeCustom];
        //用tag标记不同的button
        btn.tag = i;
    
        //设置按钮数据
        UITabBarItem *item  = self.tabBarItemArray[i];
        
        [btn setTitle:item.title forState:UIControlStateNormal];
        [btn setImage:item.image forState:UIControlStateNormal];
        [btn setImage:item.selectedImage forState:UIControlStateSelected];
        
        //添加按钮事件
        [btn addTarget:self action:@selector(selectButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        //默认选择第一个
        if (0 == i) {
            btn.selected   = YES;
            self.preButton = btn;
        }
        
        
        //添加到按钮数组中
        [self.buttonArray addObject:btn];
        //添加到tabBarView上
        [self addSubview:btn];
    }
}

/**
 *  按钮切换事件 : 切换选中的按钮
 */
-(void)selectButtonClick:(MainTabBarButton *)button
{
    self.preButton.selected = NO;
    button.selected         = YES;
    self.preButton          = button;
    
    //设置代理
    if ([self.delegate respondsToSelector:@selector(MainTabBarViewButton:selectBtnIndex:)]) {
        [self.delegate MainTabBarViewButton:self selectBtnIndex:button.tag];
    }
}

//子控件布局
-(void)layoutSubviews
{
    [super layoutSubviews];
    //设置tabBar背景
    self.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"tabbar_background"]];
    self.backgroundView.frame = self.bounds;
    [self addSubview:_backgroundView];
    
    //设置按钮frame
    CGFloat width  = self.frame.size.width / self.buttonArray.count;
    CGFloat height = self.frame.size.height;
    CGFloat y      = 0;
    CGFloat x      = 0;
    

    for (NSInteger i = 0; i < self.buttonArray.count; i++) {
        x = i * width;
        MainTabBarButton *btn = self.buttonArray[i];
        btn.frame = CGRectMake(x, y, width, height);
    }
}

@end
